package com.jiashn.minio.config;

import com.alibaba.druid.util.DruidPasswordCallback;
import com.alibaba.fastjson.JSONObject;
import com.jiashn.minio.utils.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ResourceLoader;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @author: jiangjs
 * @description:
 * @date: 2023/11/24 11:17
 **/
@Slf4j
public class RsaDBPasswordCallBack extends DruidPasswordCallback {

    private final ResourceLoader resourceLoader;
    public RsaDBPasswordCallBack(ResourceLoader resourceLoader){
        this.resourceLoader = resourceLoader;
    }

    private final static String RSA_KEYS_FILE_PATH = "classpath:/static/rsa/rsa_keys.txt";

    @Override
    public void setProperties(Properties properties){
        super.setProperties(properties);
        try(InputStream ism = resourceLoader.getResource(RSA_KEYS_FILE_PATH).getInputStream()){
            String content = new BufferedReader(new InputStreamReader(ism)).lines().collect(Collectors.joining(System.lineSeparator()));
            JSONObject object = JSONObject.parseObject(content);
            String privateKey = object.getString("private");
            String password = properties.getProperty("password");
            char[] charPassword = RSAUtil.decryptByPrivateKey(password,privateKey).toCharArray();
            super.setPassword(charPassword);
        }catch(Exception e){
            log.error("Druid密码回调报错：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
